package com.yunche.yunchebusiness.ui.activity.finance

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bumptech.glide.Glide
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.base.rx.SchedulerUtils
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.BankList
import com.yunche.yunchebusiness.entity.FinanceEntity
import com.yunche.yunchebusiness.entity.TenantBankList
import com.yunche.yunchebusiness.getSameStr
import com.yunche.yunchebusiness.mvp.contract.FinanceContract
import com.yunche.yunchebusiness.mvp.presenter.FinancePresenter
import com.yunche.yunchebusiness.network.RetrofitManager
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.utils.MyToast
import com.yunche.yunchebusiness.utils.ToastyUtils
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_get_money.*

@SuppressLint("SetTextI18n")

class GetMoneyActivity : BaseActivity(), View.OnClickListener, FinanceContract.View {
    private val mPresenter by lazy {
        FinancePresenter()
    }
    private var compositeDisposable = CompositeDisposable()

    private var bankId = 0
    private var bankListEntity = listOf<BankList>()

    override fun setLayout(): Int = R.layout.activity_get_money
    private var totalPrice = 0f

    override fun initView() {
        mPresenter.attachView(this)
    }

    override fun initData() {
        mPresenter.getTotalPrice()
        getBankList()
    }

    private fun getBankList() {
        showLoading()
        var disposable = RetrofitManager.service.getAvailableBank().compose(SchedulerUtils.ioToMain())
            .subscribe({
                hideLoading()
                if (it.resultCode == ErrorStatus.SUCCESS) {
                    this.bankListEntity = it.datas!!
                    if (bankListEntity.isNotEmpty()) {
                        tv_bank_name.text = bankListEntity[0].bankName
                        if (bankListEntity[0].account.length >= 4) {
                            tv_bank_card_num.text = "尾号：" + bankListEntity[0].account.substring(
                                bankListEntity[0].account.length - 4,
                                bankListEntity[0].account.length
                            )
                        } else {
                            tv_bank_card_num.text = "尾号：" + bankListEntity[0].account
                        }

                        bankId = bankListEntity[0].id
                        Glide.with(mContext!!).load(it.datas!![0].icon).into(iv_bank_icon)
                    }
                } else {
                    showError(it.message!!)
                }
            }, {
                hideLoading()
                showError(ExceptionHandle.handleException(it))
            })

        compositeDisposable.add(disposable)
    }

    override fun getMoneySuccess() {
        ToastyUtils.showInfo("申请提现成功")
        mPresenter.getTotalPrice()
    }

    override fun getTotalPriceSuccess(financeEntity: FinanceEntity) {
        totalPrice = financeEntity.amount
        et_get_money.hint = "可提现金额 ${totalPrice} 元（100元起提）"
        tv_get_money.text = "$totalPrice 元"
    }

    override fun getBankListSuccess(bankListEntity: List<TenantBankList>) {

    }

    private fun showBankList() {
        var bankList = arrayListOf<String>()
        for (bankListEntity in bankListEntity) {

            if (bankListEntity.account.length >= 4) {
                bankList.add(
                    bankListEntity.bankName + "(${bankListEntity.account.substring(
                        bankListEntity.account.length - 4,
                        bankListEntity.account.length
                    )})"
                )
            } else {
                bankList.add(
                    bankListEntity.bankName + "(${bankListEntity.account})"
                )
            }

        }

        val pvOptions = OptionsPickerBuilder(mContext,
            OnOptionsSelectListener { options1, _, _, _ ->
                tv_bank_name.text = bankListEntity[options1].bankName

                if (bankListEntity[options1].account.length >= 4) {
                    tv_bank_card_num.text = "尾号：" + bankListEntity[options1].account.substring(
                        bankListEntity[options1].account.length - 4,
                        bankListEntity[options1].account.length
                    )
                } else {
                    tv_bank_card_num.text = "尾号：" + bankListEntity[options1].account
                }
                bankId = bankListEntity[options1].id
                Glide.with(mContext!!).load(bankListEntity[options1].icon).into(iv_bank_icon)

            }).build<String>()
        pvOptions.setPicker(bankList)
        pvOptions.show()
    }

    override fun showError(msg: String) {
        MyToast.makeTextToast(mContext!!, msg, Toast.LENGTH_SHORT).show()
    }

    override fun showLoading() {
        CommonDialog.showLoading(mContext!!, Constant.Loading)
    }

    override fun hideLoading() {
        CommonDialog.cancle()
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_get_money -> {
                var price = et_get_money.text.toString()
                if (price.getSameStr(".") >= 2 || price.startsWith(".") || price == "") {
                    MyToast.makeTextToast(mContext!!, "金额输入有误", Toast.LENGTH_SHORT).show()
                    return
                }
                if (price.toFloat() > totalPrice) {
                    MyToast.makeTextToast(mContext!!, "金额不能大于总金额", Toast.LENGTH_SHORT).show()
                    return
                }
//                if (price.toFloat() < 100) {
//                    MyToast.makeTextToast(mContext!!, "金额不能小于100元", Toast.LENGTH_SHORT).show()
//                    return
//                }
                mPresenter.getMoney(bankId, price.toFloat(), 2)

            }
            R.id.linlay_select_bank -> {
                hideInput(linlay_select_bank)
                showBankList()
            }
        }
    }

    override fun initEvent() {
        btn_get_money.setOnClickListener(this)
        linlay_select_bank.setOnClickListener(this)
    }
}